package com.hellobike.haxing.web.file;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.hellobike.haxing.anno.NoAuth;
import com.hellobike.haxing.config.OssConfig;
import com.hellobike.haxing.order.result.Result;
import io.swagger.annotations.Api;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Api(tags = "文件上传")
@RequestMapping(value = "/file")
@RestController
@Data
@Slf4j
@NoAuth
public class FileController {
    @Autowired
    private OssConfig ossConfig;

    @Autowired
    private OSSClient ossClient;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Result<String> uploadOSS(@RequestParam(value = "file") MultipartFile file) throws Exception {
        Result<String> result = new Result<>();
        try {
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
            String ossFileName = System.currentTimeMillis() + "-" + UUID.randomUUID().toString().substring(0, 18) + suffix;
            ossClient.putObject(ossConfig.getBucketName(), ossFileName, file.getInputStream());
            ossClient.setObjectAcl(ossConfig.getBucketName(), ossFileName, CannedAccessControlList.PublicRead);
            String prefix = ossConfig.getDomain();
            if (!prefix.endsWith("/")) {
                prefix = prefix + "/";
            }
            String fileUrl = prefix + ossFileName;
            result.success("").setData(fileUrl);
            return result;
        } catch (Exception ex) {
            log.error("", ex);
            return result.error500("系统异常");
        }
    }
}
